package com.jsyxdl.conntroller;



import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.common.model.vo.BusinessObjectVO;
import com.hustcad.plm.pdm.common.model.vo.iteration.CommonIteratorVO;
import com.hustcad.plm.pdm.iteration.controller.TyplmIterationController;
import com.hustcad.plm.pdm.partbom.controller.TyplmPartController;
import com.hustcad.plm.pdm.partbom.dto.BatchAddPartDescribeLinkDTO;
import com.hustcad.plm.pdm.partbom.dto.PdmPartDescribeLinkDTO;
import com.hustcad.plm.pdm.partbom.service.TyplmPartDescribeLinkService;
import com.hustcad.plm.pdm.user.service.ErpBomService;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.part.PartReferenceLinkDO;
import com.ty.basic.response.ResponseResult;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/rest/v1/doclink")
public class DocLinkController {

    @Autowired
    ErpBomService erpBomService;
    @Autowired
    TyplmPartDescribeLinkService typlmPartDescribeLinkService;


    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws IOException {
        WorkbookProvider workbookProvider=new XSSFWorkbookFactory();
        Workbook workbook=workbookProvider.create(file.getInputStream());
        Sheet sheet=workbook.getSheetAt(0);
        Row row=sheet.getRow(0);
        Cell cell=row.getCell(1);
        String partNumbet=cell.getStringCellValue();
        cell=row.getCell(3);
        String docNumbet=cell.getStringCellValue();
        cell=row.getCell(4);
        String docType=cell.getStringCellValue();

        if("零部件编码".equals(partNumbet)==false || "文档编码".equals(docNumbet)==false || "文档类型".equals(docType)==false){
            return ResponseResult.fail("1","模板格式不正确");
        }


        List<Map<String,Object>> errlist=new ArrayList<>();
        List<Map<String,Object>> list=new ArrayList<>();

        for(int i=1;i<sheet.getPhysicalNumberOfRows();i++){
            row=sheet.getRow(i);
            cell=row.getCell(1);
            partNumbet=cell.getStringCellValue();
            cell=row.getCell(3);
            docNumbet=cell.getStringCellValue();
            cell=row.getCell(4);
            docType=cell.getStringCellValue();
            boolean add=true;
            if(partNumbet==null || "".equals(partNumbet)) {
                add=false;
            }
            if(docNumbet==null || "".equals(docNumbet)) {
                add=false;
            }
            if(docType==null || "".equals(docType)) {
                add=false;
            }

            if(add==true){
                if("参考文档".equals(docType)==false && "描述文档".equals(docType)==false){
                    add=false;
                }
            }
            Map<String,Object> map=new HashMap<>();
            map.put("partNumbet",partNumbet);
            map.put("docNumbet",docNumbet);
            map.put("docType",docType);
            map.put("indexs",i);

            if(add==false){
                map.put("error",String.format("第%d行必要参数错误",i));
                errlist.add(map);
            }
            else{
                list.add(map);
            }

        }

        if(errlist.size()>0){
            Map<String,Object> map=new HashMap<>();
            map.put("errlist", errlist);
            return ResponseResult.success(map);
        }

        for(int i=0;i<list.size();i++){
            Map<String,Object> map=list.get(i);
            List<Map<String,Object>> partList=erpBomService.getPartMaster(map);
            if(partList.size()==0){
                map.put("error",String.format("第%d行零部件不存在",map.get("indexs")));
                errlist.add(map);
            }
            else{
                map.putAll(partList.get(0));
                List<Map<String,Object>> docList=erpBomService.getDocMaster(map);
                if(docList.size()==0){
                    map.put("error",String.format("第%d行文档不存在",map.get("indexs")));
                    errlist.add(map);
                    continue;
                }
                map.putAll(docList.get(0));
            }
        }

        if(errlist.size()>0){
            Map<String,Object> map=new HashMap<>();
            map.put("errlist", errlist);
            return ResponseResult.success(map);
        }
        Map<BigInteger,Object> addTypeMap=new HashMap<>();
        for(int i=0;i<list.size();i++){
            list.get(i).put("error","成功");
            BigInteger oid=((BigDecimal) list.get(i).get("oid")).toBigInteger();
            String docTypeStr=(String) list.get(i).get("docType");
            if(addTypeMap.containsKey(oid)){
                Map<String,Object> typeMap= (Map<String, Object>) addTypeMap.get(oid);
                List<Map<String,Object>> addList= (List<Map<String, Object>>) typeMap.get(docTypeStr);
                if(addList==null){
                    addList=new ArrayList<>();
                    typeMap.put(docTypeStr,addList);
                }
                addList.add(list.get(i));
            }
            else{
                Map<String,Object> typeMap=new HashMap<>();
                List<Map<String,Object>> addList=new ArrayList<>();
                addList.add(list.get(i));
                typeMap.put(docTypeStr,addList);
                addTypeMap.put(oid,typeMap);
            }
        }

        TyplmPartController typlmPartController= SpringUtil.getBean(TyplmPartController.class);
        TyplmIterationController typlmIterationController=SpringUtil.getBean(TyplmIterationController.class);
        for(Map.Entry<BigInteger,Object> entity: addTypeMap.entrySet()){
            Map<String,Object> typeMap= (Map<String, Object>) entity.getValue();
            if(typeMap.containsKey("参考文档")){
                List<Map<String,Object>> addList= (List<Map<String, Object>>) typeMap.get("参考文档");

                List<PdmPartDescribeLinkDTO> lst=new ArrayList<>();
                for(int i=0;i<addList.size();i++){
                    String oid=((BigDecimal) list.get(i).get("defaultiteratedoid")).toString();
                    String otype=(String) list.get(i).get("defaultiteratedotype");

                    PdmPartDescribeLinkDTO pdmPartDescribeLinkDTO=new PdmPartDescribeLinkDTO();
                    pdmPartDescribeLinkDTO.setAoid(oid);
                    pdmPartDescribeLinkDTO.setAotype(otype);

                    pdmPartDescribeLinkDTO.setOid(((BigDecimal) list.get(i).get("defauloid")).toString());
                    pdmPartDescribeLinkDTO.setMasteredoid(((BigDecimal) list.get(i).get("docoid")).toBigInteger());

                    lst.add(pdmPartDescribeLinkDTO);
                }
                try {
                    typlmPartController.batchInsertPartReferenceLink(lst);

                }
                catch (Exception e){
                    e.printStackTrace();
                }

            }
            if(typeMap.containsKey("描述文档")){
                List<Map<String,Object>> addList= (List<Map<String, Object>>) typeMap.get("描述文档");

                List<BatchAddPartDescribeLinkDTO> batchAddPartDescribeLinkDTO=new ArrayList<>();
                BatchAddPartDescribeLinkDTO batchAddPartDescribeLinkDTO1=new BatchAddPartDescribeLinkDTO();

                CommonIteratorVO commonIteratorVO=new CommonIteratorVO();
                commonIteratorVO.setId(((BigDecimal) list.get(0).get("partoid")).toString());
                commonIteratorVO.setTypeDefName((String) list.get(0).get("partotype"));
                ResponseResult<BusinessObjectVO> responseResult=typlmIterationController.checkOut(commonIteratorVO);

                List<IdentifierEntity> refObj=new ArrayList<>();
                for(int i=0;i<addList.size();i++){
                    BigInteger oid=responseResult.getData().getId();
                    String otype=responseResult.getData().getOtype();
                    batchAddPartDescribeLinkDTO1.setOid(oid);
                    batchAddPartDescribeLinkDTO1.setOtype(otype);
                    IdentifierEntity identifierEntity=new IdentifierEntity();
                    identifierEntity.setOid(((BigDecimal) list.get(i).get("defauloid")).toBigInteger());
                    identifierEntity.setOtype((String) list.get(i).get("defaulotype"));
                    refObj.add(identifierEntity);
                }
                batchAddPartDescribeLinkDTO1.setRefObj(refObj);
                batchAddPartDescribeLinkDTO.add(batchAddPartDescribeLinkDTO1);

                try {
                    this.typlmPartDescribeLinkService.batchAddPartDescribeLink(batchAddPartDescribeLinkDTO);
                }
                catch (Exception e){

                }

                commonIteratorVO.setId(responseResult.getData().getId().toString());
                commonIteratorVO.setTypeDefName(responseResult.getData().getOtype());
                typlmIterationController.checkIn(commonIteratorVO);
            }

        }




        Map<String,Object> map=new HashMap<>();
        map.put("list", list);
        return ResponseResult.success(map);
    }


}
